package io.gitee.bowen_lee.netty.bowen.client;

import java.io.IOException;
import java.net.InetSocketAddress;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 
 * @author Bowen
 * @since 2022-01-10 10:59:44
 */
public class MyNetty {
  /**
   * 测试 NioEventLoopGroup <br/>
   * 用起来是个线程池的样子
   */
  public void nioEventLoopGroup() {
    NioEventLoopGroup selectors = new NioEventLoopGroup(2);
    selectors.execute(() -> {
      while (true) {
        System.out.println("hello world!" + Thread.currentThread().getId());
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    selectors.execute(() -> {
      while (true) {
        System.out.println("hello world!" + Thread.currentThread().getId());
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    try {
      System.in.read();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 客户端
   * 
   * @throws Exception
   */
  public void NettyClient() throws Exception {
    NioEventLoopGroup eventLoop = new NioEventLoopGroup();

    NioSocketChannel channel = new NioSocketChannel();
    eventLoop.register(channel);

    // 这个connect 是异步的。 所以要等 连接线程执行完毕之后 。 才能执行 后续步骤
    ChannelFuture channelFuture = channel.connect(new InetSocketAddress("127.0.0.1", 9090));
    channelFuture.sync();

    // 读/写 操作
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast("", new MyChannelHandle() {
      /**
       * 业务代码
       */
      @Override
      public void println(ChannelHandlerContext ctx, String str) {
        // 客户端收到服务端的‘收到’，回复Bye Bye!
        if ("received!".equals(str)) {
          System.out.println("发送 Bye Bye!");
          ctx.writeAndFlush(Unpooled.copiedBuffer("Bye Bye!".getBytes()));
        }
      }

    });

    ByteBuf clientMsg = Unpooled.copiedBuffer("hello world".getBytes());
    System.out.println("发送hello world! ");
    channel.writeAndFlush(clientMsg);

    // 扩展1. channel.writeAndFlush() 也是异步的 有 futrue

    // 扩展2. 等待服务端断开
    channelFuture.channel().closeFuture().sync();
    System.out.println("断开链接了");
  }

}
